package it.pir.es01ProduttoreConsumatore;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	private static final int PORT=7777;
	private ServerBuffer<Pacchetto> sb;
	private static int numPkt;
	/* FARE IL SINGLETON*/
	public Server(){
		sb = new ServerBuffer<Pacchetto>();
	}
	
	public ServerBuffer<Pacchetto> getServerBuffer(){
		return sb;
	}
	
	@SuppressWarnings("resource")
	public static void main(String args[]) throws IOException, ClassNotFoundException {
		
		ServerSocket servSock = new ServerSocket(PORT);
		Server server = new Server();
		
		System.out.println("-------- SERVER PRODUTTORE CONSUMATORE --------\n\n");
		while (true) {
			Socket s=servSock.accept();
		
			/* Deserializzazione */
			ObjectInputStream in = new ObjectInputStream(s.getInputStream());
			Pacchetto pkt = (Pacchetto)in.readObject();
			
			if(pkt.isProduttore()){
				numPkt++;
				pkt.setNumPacchetto(numPkt);
				ServerProduttore sp = new ServerProduttore(pkt,server.getServerBuffer());
				Thread t = new Thread(sp);
				t.start();
			}
			else{
				ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
				ServerConsumatore sc = new ServerConsumatore(out,server.getServerBuffer());

				Thread t = new Thread(sc);
				t.start();
			}
			//s.close();
		}
		
		
	}
}
